package repository

import (
	"context"
	"database/sql"
	"fmt"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/blog/model"

	"github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/cache"
)

type (
	// TermRepository is an interface to be customized, add more methods here,
	// and implement the added methods in customTermRepository.
	TermRepository interface {
		FindOne(ctx context.Context, id uint64) (*model.BlogTerm, error)
		FindOneWithExpire(
			ctx context.Context,
			id uint64,
			expire time.Duration,
		) (*model.BlogTerm, error)
		FindOneNoCache(
			ctx context.Context,
			conn boil.ContextExecutor,
			id uint64,
		) (*model.BlogTerm, error)
		GetList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.BlogTerm, int64, error) // ##24.11.27##
		Insert(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.BlogTerm,
			rel *model.BlogTermRel,
		) error // ##24.11.27##
		Update(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.BlogTerm,
			rel *model.BlogTermRel,
		) error // ##24.11.27##
		UpdateBatch(ctx context.Context, tx boil.ContextExecutor, ids []uint64, cols model.M) error
		SoftDelete(ctx context.Context, tx boil.ContextExecutor, id uint64) error // ##24.11.27##
		Restore(ctx context.Context, tx boil.ContextExecutor, id uint64) error    // ##24.11.27##
		ForceDelete(ctx context.Context, tx boil.ContextExecutor, id uint64) error
		ForceDeleteBatch(ctx context.Context, tx boil.ContextExecutor, ids []uint64) error

		SyncQiniu(ctx context.Context, id uint64, mediaId uint64, url string) (int64, error) // ##25.02.18##

		GetMedia(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.BlogAttachmentRelationship, int64, error) // ##24.11.27##
		GetMeta(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.BlogTermMetum, int64, error) // ##24.11.27##
		GetRelationshipList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.BlogTermRelationship, int64, error) // ##24.11.08##
		UpdateMeta(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.BlogTermMetum,
		) (err error)
	}

	customTermRepository struct {
		modelx.CachedConn
		mysqlConn           *sql.DB
		cacheIdPrefix       string
		cacheIdExpirePrefix string
	}
)

// NewTermRepository returns a repository for the database table.
func NewTermRepository(mysqlConn *sql.DB, cacheConf cache.CacheConf) TermRepository {
	return &customTermRepository{
		CachedConn:          modelx.NewConn(mysqlConn, cacheConf),
		mysqlConn:           mysqlConn,
		cacheIdPrefix:       "cache:cms:terms:id:",
		cacheIdExpirePrefix: "cache:cms:terms:id:expire:",
	}
}

func (r *customTermRepository) FindOne(
	ctx context.Context,
	id uint64,
) (*model.BlogTerm, error) {
	cacheIdKey := r.formatPrimary(id)
	var resp model.BlogTerm
	err := r.QueryCtx(ctx, &resp, cacheIdKey, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindBlogTerm(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.BlogTerm) = *data

		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customTermRepository) FindOneWithExpire(
	ctx context.Context,
	id uint64,
	expire time.Duration,
) (*model.BlogTerm, error) {
	cacheIdKey := r.formatPrimary(id)
	var resp model.BlogTerm
	err := r.QueryWithExpireCtx(ctx, &resp, cacheIdKey, expire, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindBlogTerm(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.BlogTerm) = *data

		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customTermRepository) FindOneNoCache(
	ctx context.Context,
	conn boil.ContextExecutor,
	id uint64,
) (*model.BlogTerm, error) {
	var db boil.ContextExecutor = r.mysqlConn
	if conn != nil {
		db = conn
	}
	data, err := model.FindBlogTerm(ctx, db, id)
	switch err {
	case nil:
		return data, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customTermRepository) GetList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.BlogTerm, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	var statistic bool
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogTermColumns.TermID+" DESC"))
					mods = append(mods, model.BlogTermWhere.TermID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogTermColumns.TermID+" ASC"))
					mods = append(mods, model.BlogTermWhere.TermID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		case "search":
			if val, ok := v.(string); ok && len(val) > 0 { // 搜索
				likeVal := fmt.Sprintf("%%%s%%", val)
				mods = append(mods, qm.Where(fmt.Sprintf(
					"(%s LIKE ? OR %s LIKE ?)",
					model.BlogTermColumns.Name,
					model.BlogTermColumns.Slug), likeVal, likeVal))
			}
		case "statistic":
			if val, ok := v.(string); ok && val == "1" { // 按 Status 统计
				statistic = true
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.BlogTermColumns.TermID:
			mods = append(mods, modelx.GetIntMods(model.BlogTermColumns.TermID, opMap)...)
		case model.BlogTermColumns.Name:
			mods = append(mods, modelx.GetStringMods(model.BlogTermColumns.Name, opMap)...)
		case model.BlogTermColumns.Slug:
			mods = append(mods, modelx.GetStringMods(model.BlogTermColumns.Slug, opMap)...)
		case model.BlogTermColumns.Taxonomy:
			mods = append(mods, modelx.GetIntMods(model.BlogTermColumns.Taxonomy, opMap)...)
		case model.BlogTermColumns.ParentID:
			mods = append(mods, modelx.GetIntMods(model.BlogTermColumns.ParentID, opMap)...)
		case model.BlogTermColumns.TermGroup:
			mods = append(mods, modelx.GetIntMods(model.BlogTermColumns.TermGroup, opMap)...)
		case model.BlogTermColumns.Count:
			mods = append(mods, modelx.GetIntMods(model.BlogTermColumns.Count, opMap)...)
		case model.BlogTermColumns.Sort:
			mods = append(mods, modelx.GetIntMods(model.BlogTermColumns.Sort, opMap)...)
		case model.BlogTermColumns.Status:
			mods = append(mods, modelx.GetIntMods(model.BlogTermColumns.Status, opMap)...)
		case model.BlogTermColumns.CreatedAt:
			mods = append(mods, modelx.GetTimeMods(model.BlogTermColumns.CreatedAt, opMap)...)
		case model.BlogTermColumns.UpdatedAt:
			mods = append(mods, modelx.GetTimeMods(model.BlogTermColumns.UpdatedAt, opMap)...)
		case model.BlogTermColumns.DeletedAt:
			mods = append(mods, modelx.GetTimeMods(model.BlogTermColumns.DeletedAt, opMap)...)
		}
	}

	if statistic {
		mods = append(mods, qm.Select(fmt.Sprintf(
			"%s, count(%s) as %s",
			model.BlogTermColumns.Status,
			model.BlogTermColumns.Status,
			model.BlogTermColumns.Count,
		)))
		mods = append(mods, qm.GroupBy(model.BlogTermColumns.Status))
		preList, preErr := model.BlogTerms(mods...).All(ctx, r.mysqlConn)
		if preErr != nil {
			err = preErr
			return
		}

		return preList, 0, nil
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.BlogTerms(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.BlogTermColumns.TermID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.BlogTerms(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customTermRepository) Insert(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.BlogTerm,
	rel *model.BlogTermRel,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		err := data.Insert(ctx, db, boil.Infer())
		if err != nil {
			return err
		}

		if rel == nil {
			return nil
		}

		termId := data.TermID
		if len(rel.Meta) > 0 {
			for _, v := range rel.Meta {
				v.TermID = termId
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		if len(rel.Media) > 0 {
			for _, v := range rel.Media {
				v.ObjectID = termId
				v.ObjectType = data.Taxonomy + globalkey.PostTypeTermOffset
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customTermRepository) Update(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.BlogTerm,
	rel *model.BlogTermRel,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		blacklist := []string{
			model.BlogTermColumns.TermID,
			model.BlogTermColumns.DeletedAt,
		}
		if rel != nil && len(rel.Blacklist) > 0 {
			blacklist = append(blacklist, rel.Blacklist...)
		}
		rowsAff, err := data.Update(ctx, db, boil.Blacklist(blacklist...))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		if rel == nil {
			return nil
		}

		termId := data.TermID
		if len(rel.Meta) > 0 {
			for _, v := range rel.Meta {
				if v.MetaID > 0 {
					_, err = v.Update(ctx, db, boil.Blacklist(
						model.BlogTermMetumColumns.MetaID,
						model.BlogTermMetumColumns.TermID,
						model.BlogTermMetumColumns.MetaKey,
					))
					if err != nil {
						return err
					}
				} else {
					v.TermID = termId
					err = v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}
		}

		if len(rel.Media) > 0 {
			for _, v := range rel.Media {
				if v.AttachmentRelationshipID > 0 {
					_, err = v.Update(ctx, db, boil.Blacklist(
						model.BlogAttachmentRelationshipColumns.AttachmentRelationshipID,
						model.BlogAttachmentRelationshipColumns.ObjectID,
						model.BlogAttachmentRelationshipColumns.ObjectType,
						model.BlogAttachmentRelationshipColumns.AttachmentID,
					))
					if err != nil {
						return err
					}
				} else {
					v.ObjectID = termId
					v.ObjectType = data.Taxonomy + globalkey.PostTypeTermOffset
					err = v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}
		}

		if len(rel.DelMetaIds) > 0 {
			var mods []qm.QueryMod
			mods = append(mods, model.BlogTermMetumWhere.MetaID.IN(rel.DelMetaIds))
			_, err = model.BlogTermMeta(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}
		}

		if len(rel.DelMediaIds) > 0 {
			var mods []qm.QueryMod
			mods = append(mods, model.BlogAttachmentRelationshipWhere.AttachmentRelationshipID.IN(rel.DelMediaIds))
			_, err = model.BlogAttachmentRelationships(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customTermRepository) UpdateBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
	cols model.M,
) error {
	if len(ids) > 0 {
		err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
			var db boil.ContextExecutor
			if tx != nil {
				db = tx
			} else {
				db = conn
			}

			var mods []qm.QueryMod
			mods = append(mods, model.BlogTermWhere.TermID.IN(ids))

			rowsAff, err := model.BlogTerms(mods...).UpdateAll(ctx, db, cols)
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotUpdated
			}

			return nil
		}, r.formatPrimaries(ids)...)

		return err
	}

	return nil
}

func (r *customTermRepository) SoftDelete(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.Status == uint8(globalkey.StatusDeleted) {
		return nil
	}

	data.DelStatus = data.Status
	data.Status = uint8(globalkey.StatusDeleted)
	data.DeletedAt = null.TimeFrom(time.Now())
	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Whitelist(
			model.BlogTermColumns.DelStatus,
			model.BlogTermColumns.Status,
			model.BlogTermColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customTermRepository) Restore(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.Status != uint8(globalkey.StatusDeleted) {
		return nil
	}

	data.Status = data.DelStatus
	data.DeletedAt = null.TimeFromPtr(nil)
	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Whitelist(
			model.BlogTermColumns.Status,
			model.BlogTermColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customTermRepository) ForceDelete(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Delete(ctx, db)
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotDeleted
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customTermRepository) ForceDeleteBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
) error {
	if len(ids) > 0 {
		err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
			var db boil.ContextExecutor
			if tx != nil {
				db = tx
			} else {
				db = conn
			}

			var mods []qm.QueryMod
			mods = append(mods, model.BlogTermWhere.TermID.IN(ids))
			rowsAff, err := model.BlogTerms(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotDeleted
			}

			var metaMods []qm.QueryMod
			metaMods = append(metaMods, model.BlogTermMetumWhere.TermID.IN(ids))
			_, err = model.BlogTermMeta(metaMods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}

			var mediaMods []qm.QueryMod
			mediaMods = append(mediaMods, model.BlogTermRelationshipWhere.TermID.IN(ids))
			_, err = model.BlogTermRelationships(mediaMods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}

			return nil
		}, r.formatPrimaries(ids)...)

		return err
	}

	return nil
}

func (r *customTermRepository) SyncQiniu(ctx context.Context, id uint64, mediaId uint64, url string) (rowsAff int64, err error) {
	var mods []qm.QueryMod
	mods = append(mods, model.BlogAttachmentRelationshipWhere.ObjectID.EQ(id))
	mods = append(mods, model.BlogAttachmentRelationshipWhere.AttachmentID.EQ(mediaId))
	list, err := model.BlogAttachmentRelationships(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if len(list) == 0 {
		return
	}

	urlStr := url + "?" + strconv.FormatUint(mediaId, 10)

	for _, item := range list {
		if len(item.AttachmentSource) == 0 {
			continue
		}

		var subMods []qm.QueryMod
		var metaMods []qm.QueryMod
		switch int32(item.ObjectType) {
		case globalkey.AttachmentLogTypeKnowledgeBase:
			subMods = append(subMods, model.BlogKnowledgeBaseDetailWhere.KnowledgeBaseID.EQ(item.ObjectID))
			subList, subErr := model.BlogKnowledgeBaseDetails(subMods...).All(ctx, r.mysqlConn)
			if subErr != nil {
				logx.Errorw("SyncQiniu KnowledgeBaseDetail error", logx.Field("detail", subErr.Error()))
				logrus.Info(fmt.Sprintf("SyncQiniu KnowledgeBaseDetail error, entryId: %d, err: %+v", item.ObjectID, subErr))
				continue
			}

			for _, subItem := range subList {
				subItem.PostContent = strings.Replace(subItem.PostContent, item.AttachmentSource, urlStr, -1)
				subItem.PostContentFiltered = strings.Replace(subItem.PostContentFiltered, item.AttachmentSource, urlStr, -1)
				_, subErr = subItem.Update(ctx, r.mysqlConn, boil.Blacklist(
					model.BlogKnowledgeBaseDetailColumns.DetailID,
					model.BlogKnowledgeBaseDetailColumns.KnowledgeBaseID,
				))
				if subErr != nil {
					logx.Errorw("SyncQiniu KnowledgeBaseDetail update error", logx.Field("detail", subErr.Error()))
					logrus.Info(fmt.Sprintf("SyncQiniu KnowledgeBaseDetail update error, entryId: %d, err: %+v", item.ObjectID, subErr))
				}
			}

			metaMods = append(metaMods, model.BlogKnowledgeBaseMetumWhere.KnowledgeBaseID.EQ(item.ObjectID))
			metaMods = append(metaMods, model.BlogKnowledgeBaseMetumWhere.MetaKey.EQ("_thumbnail_url"))
			metaList, err := model.BlogKnowledgeBaseMeta(metaMods...).All(ctx, r.mysqlConn)
			if err != nil {
				logx.Errorw("SyncQiniu BlogKnowledgeBaseMeta error", logx.Field("detail", err.Error()))
				logrus.Info(fmt.Sprintf("SyncQiniu BlogKnowledgeBaseMeta error, entryId: %d, err: %+v", item.ObjectID, err))
				continue
			}

			for _, metum := range metaList {
				metum.MetaValue = null.StringFrom(url)
				_, err = metum.Update(ctx, r.mysqlConn, boil.Whitelist(
					model.BlogKnowledgeBaseMetumColumns.MetaValue,
				))
				if err != nil {
					logx.Errorw("SyncQiniu BlogKnowledgeBaseMeta update error", logx.Field("detail", err.Error()))
					logrus.Info(fmt.Sprintf("SyncQiniu BlogKnowledgeBaseMeta update error, productId: %d, err: %+v", item.ObjectID, err))
				}
			}
		case globalkey.AttachmentLogTypePost:
			subMods = append(subMods, model.BlogPostDetailWhere.PostID.EQ(item.ObjectID))
			subList, subErr := model.BlogPostDetails(subMods...).All(ctx, r.mysqlConn)
			if subErr != nil {
				logx.Errorw("SyncQiniu PostDetail error", logx.Field("detail", subErr.Error()))
				logrus.Info(fmt.Sprintf("SyncQiniu PostDetail error, postId: %d, err: %+v", item.ObjectID, subErr))
				continue
			}

			for _, subItem := range subList {
				subItem.PostContent = strings.Replace(subItem.PostContent, item.AttachmentSource, urlStr, -1)
				subItem.PostContentFiltered = strings.Replace(subItem.PostContentFiltered, item.AttachmentSource, urlStr, -1)
				_, subErr = subItem.Update(ctx, r.mysqlConn, boil.Blacklist(
					model.BlogPostDetailColumns.DetailID,
					model.BlogPostDetailColumns.PostID,
				))
				if subErr != nil {
					logx.Errorw("SyncQiniu PostDetail update error", logx.Field("detail", subErr.Error()))
					logrus.Info(fmt.Sprintf("SyncQiniu PostDetail update error, postId: %d, err: %+v", item.ObjectID, subErr))
				}
			}

			metaMods = append(metaMods, model.BlogPostMetumWhere.PostID.EQ(item.ObjectID))
			metaMods = append(metaMods, model.BlogPostMetumWhere.MetaKey.EQ("_thumbnail_url"))
			metaList, err := model.BlogPostMeta(metaMods...).All(ctx, r.mysqlConn)
			if err != nil {
				logx.Errorw("SyncQiniu BlogPostMeta error", logx.Field("detail", err.Error()))
				logrus.Info(fmt.Sprintf("SyncQiniu BlogPostMeta error, postId: %d, err: %+v", item.ObjectID, err))
				continue
			}

			for _, metum := range metaList {
				metum.MetaValue = null.StringFrom(url)
				_, err = metum.Update(ctx, r.mysqlConn, boil.Whitelist(
					model.BlogPostMetumColumns.MetaValue,
				))
				if err != nil {
					logx.Errorw("SyncQiniu BlogPostMeta update error", logx.Field("detail", err.Error()))
					logrus.Info(fmt.Sprintf("SyncQiniu BlogPostMeta update error, postId: %d, err: %+v", item.ObjectID, err))
				}
			}
		case globalkey.AttachmentLogTypePage:
			subMods = append(subMods, model.BlogPageDetailWhere.PageID.EQ(item.ObjectID))
			subList, subErr := model.BlogPageDetails(subMods...).All(ctx, r.mysqlConn)
			if subErr != nil {
				logx.Errorw("SyncQiniu PageDetail error", logx.Field("detail", subErr.Error()))
				logrus.Info(fmt.Sprintf("SyncQiniu PageDetail error, pageId: %d, err: %+v", item.ObjectID, subErr))
				continue
			}

			for _, subItem := range subList {
				subItem.PostContent = strings.Replace(subItem.PostContent, item.AttachmentSource, urlStr, -1)
				subItem.PostContentFiltered = strings.Replace(subItem.PostContentFiltered, item.AttachmentSource, urlStr, -1)
				_, subErr = subItem.Update(ctx, r.mysqlConn, boil.Blacklist(
					model.BlogPageDetailColumns.DetailID,
					model.BlogPageDetailColumns.PageID,
				))
				if subErr != nil {
					logx.Errorw("SyncQiniu PageDetail update error", logx.Field("detail", subErr.Error()))
					logrus.Info(fmt.Sprintf("SyncQiniu PageDetail update error, pageId: %d, err: %+v", item.ObjectID, subErr))
				}
			}

			metaMods = append(metaMods, model.BlogPageMetumWhere.PageID.EQ(item.ObjectID))
			metaMods = append(metaMods, model.BlogPageMetumWhere.MetaKey.EQ("_thumbnail_url"))
			metaList, err := model.BlogPageMeta(metaMods...).All(ctx, r.mysqlConn)
			if err != nil {
				logx.Errorw("SyncQiniu BlogPageMeta error", logx.Field("detail", err.Error()))
				logrus.Info(fmt.Sprintf("SyncQiniu BlogPageMeta error, pageId: %d, err: %+v", item.ObjectID, err))
				continue
			}

			for _, metum := range metaList {
				metum.MetaValue = null.StringFrom(url)
				_, err = metum.Update(ctx, r.mysqlConn, boil.Whitelist(
					model.BlogPageMetumColumns.MetaValue,
				))
				if err != nil {
					logx.Errorw("SyncQiniu BlogPageMeta update error", logx.Field("detail", err.Error()))
					logrus.Info(fmt.Sprintf("SyncQiniu BlogPageMeta update error, pageId: %d, err: %+v", item.ObjectID, err))
				}
			}
		case globalkey.AttachmentLogTypeTerm:
			subMods = append(subMods, model.BlogTermWhere.TermID.EQ(item.ObjectID))
			subList, subErr := model.BlogTerms(subMods...).All(ctx, r.mysqlConn)
			if subErr != nil {
				logx.Errorw("SyncQiniu BlogTerm error", logx.Field("detail", subErr.Error()))
				logrus.Info(fmt.Sprintf("SyncQiniu BlogTerm error, termId: %d, err: %+v", item.ObjectID, subErr))
				continue
			}

			for _, subItem := range subList {
				subItem.Description = strings.Replace(subItem.Description, item.AttachmentSource, urlStr, -1)
				subItem.DescriptionFiltered = strings.Replace(subItem.DescriptionFiltered, item.AttachmentSource, urlStr, -1)
				_, subErr = subItem.Update(ctx, r.mysqlConn, boil.Blacklist(
					model.BlogTermColumns.TermID,
					model.BlogTermColumns.UpdatedAt,
				))
				if subErr != nil {
					logx.Errorw("SyncQiniu BlogTerm update error", logx.Field("detail", subErr.Error()))
					logrus.Info(fmt.Sprintf("SyncQiniu BlogTerm update error, termId: %d, err: %+v", item.ObjectID, subErr))
				}
			}

			metaMods = append(metaMods, model.BlogTermMetumWhere.TermID.EQ(item.ObjectID))
			metaMods = append(metaMods, model.BlogTermMetumWhere.MetaKey.EQ("_thumbnail_url"))
			metaList, err := model.BlogTermMeta(metaMods...).All(ctx, r.mysqlConn)
			if err != nil {
				logx.Errorw("SyncQiniu BlogTermMeta error", logx.Field("detail", err.Error()))
				logrus.Info(fmt.Sprintf("SyncQiniu BlogTermMeta error, termId: %d, err: %+v", item.ObjectID, err))
				continue
			}

			for _, metum := range metaList {
				metum.MetaValue = null.StringFrom(url)
				_, err = metum.Update(ctx, r.mysqlConn, boil.Whitelist(
					model.BlogTermMetumColumns.MetaValue,
				))
				if err != nil {
					logx.Errorw("SyncQiniu BlogTermMeta update error", logx.Field("detail", err.Error()))
					logrus.Info(fmt.Sprintf("SyncQiniu BlogTermMeta update error, termId: %d, err: %+v", item.ObjectID, err))
				}
			}
		}
	}

	rowsAff, err = model.BlogAttachmentRelationships(mods...).UpdateAll(ctx, r.mysqlConn, model.M{
		model.BlogAttachmentRelationshipColumns.AttachmentImageURL: url,
	})

	return
}

func (r *customTermRepository) getCacheKeys(data *model.BlogTerm) []string {
	if data == nil {
		return []string{}
	}

	cacheIdKey := r.formatPrimary(data.TermID)
	cacheKeys := []string{
		cacheIdKey,
	}

	return cacheKeys
}

func (r *customTermRepository) formatPrimary(primary any) string {
	return fmt.Sprintf("%s%v", r.cacheIdPrefix, primary)
}

func (r *customTermRepository) formatPrimaries(primaries []uint64) []string {
	var resp []string
	for _, primary := range primaries {
		resp = append(resp, r.formatPrimary(primary))
	}

	return resp
}

func (r *customTermRepository) queryPrimary(ctx context.Context, conn *sql.DB, v, primary any) error {
	data, err := model.FindBlogTerm(ctx, conn, primary.(uint64))
	if err != nil {
		return err
	}

	*v.(*model.BlogTerm) = *data

	return nil
}

func (r *customTermRepository) GetMedia(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.BlogAttachmentRelationship, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogAttachmentRelationshipColumns.AttachmentRelationshipID+" DESC"))
					mods = append(mods, model.BlogAttachmentRelationshipWhere.AttachmentRelationshipID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogAttachmentRelationshipColumns.AttachmentRelationshipID+" ASC"))
					mods = append(mods, model.BlogAttachmentRelationshipWhere.AttachmentRelationshipID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.BlogAttachmentRelationshipColumns.AttachmentRelationshipID:
			mods = append(mods, modelx.GetIntMods(model.BlogAttachmentRelationshipColumns.AttachmentRelationshipID, opMap)...)
		case model.BlogAttachmentRelationshipColumns.ObjectID:
			mods = append(mods, modelx.GetIntMods(model.BlogAttachmentRelationshipColumns.ObjectID, opMap)...)
		case model.BlogAttachmentRelationshipColumns.ObjectType:
			mods = append(mods, modelx.GetIntMods(model.BlogAttachmentRelationshipColumns.ObjectType, opMap)...)
		case model.BlogAttachmentRelationshipColumns.AttachmentID:
			mods = append(mods, modelx.GetIntMods(model.BlogAttachmentRelationshipColumns.AttachmentID, opMap)...)
		case model.BlogAttachmentRelationshipColumns.AttachmentThumbnail:
			mods = append(mods, modelx.GetIntMods(model.BlogAttachmentRelationshipColumns.AttachmentThumbnail, opMap)...)
		case model.BlogAttachmentRelationshipColumns.AttachmentOrder:
			mods = append(mods, modelx.GetIntMods(model.BlogAttachmentRelationshipColumns.AttachmentOrder, opMap)...)
		case model.BlogAttachmentRelationshipColumns.AttachmentSource:
			mods = append(mods, modelx.GetStringMods(model.BlogAttachmentRelationshipColumns.AttachmentSource, opMap)...)
		case model.BlogAttachmentRelationshipColumns.AttachmentImageURL:
			mods = append(mods, modelx.GetStringMods(model.BlogAttachmentRelationshipColumns.AttachmentImageURL, opMap)...)
		case model.BlogAttachmentRelationshipColumns.AttachmentImageAlt:
			mods = append(mods, modelx.GetStringMods(model.BlogAttachmentRelationshipColumns.AttachmentImageAlt, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.BlogAttachmentRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.BlogAttachmentRelationshipColumns.AttachmentRelationshipID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.BlogAttachmentRelationships(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customTermRepository) GetMeta(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.BlogTermMetum, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogTermMetumColumns.MetaID+" DESC"))
					mods = append(mods, model.BlogTermMetumWhere.MetaID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogTermMetumColumns.MetaID+" ASC"))
					mods = append(mods, model.BlogTermMetumWhere.MetaID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.BlogTermMetumColumns.MetaID:
			mods = append(mods, modelx.GetIntMods(model.BlogTermMetumColumns.MetaID, opMap)...)
		case model.BlogTermMetumColumns.TermID:
			mods = append(mods, modelx.GetIntMods(model.BlogTermMetumColumns.TermID, opMap)...)
		case model.BlogTermMetumColumns.MetaKey:
			mods = append(mods, modelx.GetStringMods(model.BlogTermMetumColumns.MetaKey, opMap)...)
		case model.BlogTermMetumColumns.MetaValue:
			mods = append(mods, modelx.GetIntMods(model.BlogTermMetumColumns.MetaValue, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.BlogTermMeta(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.BlogTermMetumColumns.MetaID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.BlogTermMeta(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customTermRepository) GetRelationshipList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.BlogTermRelationship, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogTermRelationshipColumns.TermRelationshipID+" DESC"))
					mods = append(mods, model.BlogTermRelationshipWhere.TermRelationshipID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.BlogTermRelationshipColumns.TermRelationshipID+" ASC"))
					mods = append(mods, model.BlogTermRelationshipWhere.TermRelationshipID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if val, ok := v.(string); ok && len(val) > 0 {
				selectCol = val
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.BlogTermRelationshipColumns.TermRelationshipID:
			mods = append(mods, modelx.GetIntMods(model.BlogTermRelationshipColumns.TermRelationshipID, opMap)...)
		case model.BlogTermRelationshipColumns.ObjectID:
			mods = append(mods, modelx.GetIntMods(model.BlogTermRelationshipColumns.ObjectID, opMap)...)
		case model.BlogTermRelationshipColumns.ObjectType:
			mods = append(mods, modelx.GetIntMods(model.BlogTermRelationshipColumns.ObjectType, opMap)...)
		case model.BlogTermRelationshipColumns.TermID:
			mods = append(mods, modelx.GetIntMods(model.BlogTermRelationshipColumns.TermID, opMap)...)
		case model.BlogTermRelationshipColumns.StickyType:
			mods = append(mods, modelx.GetIntMods(model.BlogTermRelationshipColumns.StickyType, opMap)...)
		case model.BlogTermRelationshipColumns.TermOrder:
			mods = append(mods, modelx.GetIntMods(model.BlogTermRelationshipColumns.TermOrder, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.BlogTermRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.BlogTermRelationshipColumns.TermRelationshipID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.BlogTermRelationships(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customTermRepository) UpdateMeta(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.BlogTermMetum,
) (err error) {
	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Blacklist(
			model.BlogTermMetumColumns.TermID,
			model.BlogTermMetumColumns.MetaKey,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}
		return nil
	}, r.getCacheKeys(&model.BlogTerm{TermID: data.TermID})...)

	return nil
}
